import Vue from 'vue'
import Router from 'vue-router'
import Login from './components/Login.vue'
import Home from './components/Home.vue'
import Welcome from './components/Welcome.vue'
import User from './components/User.vue'



Vue.use(Router)

const router= new Router({
  routes: [
    // 重定向，让用户打开直接进入登录页面
    {path:'/',redirect:'/login'},
    {path:'/login',component:Login},
    {
      path:'/home',
      component:Home,
      redirect:'/welcome',
      children:[{path:'/welcome',component:Welcome},{path:'/users',component:User}]
    }

  ]
})

// 挂载路由导航守卫:拦截路由跳转的，如果登录了可以访问首页，如果没有登录要返回登录界面
// 只要调用beforEach()，就开始拦截，只有后面的next()调用才能发生跳转
router.beforeEach((to,from,next)=>{
  // to:要去哪里
  // from:
  // next:
  if(to.path =='/login') return next()
  // 获取token
  const tokenStr=window.sessionStorage.getItem('token')
  if(!tokenStr) return next('/login')
  next()
})

export default router
